#ifndef XG_POSTGRESQLCONNECT_H
#define XG_POSTGRESQLCONNECT_H
//////////////////////////////////////////////////////////////
#include <libpq-fe.h>
#include "DBConnect.h"

class PostgreSQLRowData : public RowData
{
	friend class PostgreSQLQueryResult;

	bool m_bNull = true;
	int m_iRowNum = 0;
	PGresult* res = NULL;

public:
	CONSTRUCTOR_FORBID_COPY(PostgreSQLRowData)

	bool isNull();
	string getString(int index);
	int getDataLength(int index);
	PostgreSQLRowData(PGresult* res);
	int getData(int index, char* data, int len);
};

class PostgreSQLQueryResult : public QueryResult
{
	friend class PostgreSQLConnect;

	int iCurIndex = 0;
	int iRowCount = 0;
	PGconn* m_pConn = NULL;
	PGresult* m_pSQLRes = NULL;

public:
	CONSTRUCTOR_FORBID_COPY(PostgreSQLQueryResult)

	~PostgreSQLQueryResult();
	PostgreSQLQueryResult(PGresult* res, PGconn* conn);

	int rows();
	int cols();
	void close();
	sp<RowData> next();
	bool seek(int ofs);
	int getErrorCode();
	string getErrorString();
	string getColumnName(int index);
	bool getColumnData(ColumnData& data, int index);
};

class PostgreSQLConnect : public DBConnect
{
	PGconn* m_pConn = NULL;

	int bind(void* stmt, const vector<DBData*>& vec);

public:
	CONSTRUCTOR_FORBID_COPY(PostgreSQLConnect)
	
	void close();
	bool commit();
	bool rollback();
	~PostgreSQLConnect();
	const char* getTableSQL();
	const char* getSystemName();
	bool begin(bool commited = true);
	bool setCharset(const string& charset);
	int getPrimaryKeys(vector<string>& vec, const string& tabname);
	bool connect(const string& host, int port, const string& name, const string& user, const string& password);

	int getErrorCode();
	string getErrorString();
	int execute(const string& sqlcmd);
	sp<QueryResult> query(const string& sqlcmd);
	int execute(const string& sqlcmd, const vector<DBData*>& vec);
	sp<QueryResult> query(const string& sqlcmd, const vector<DBData*>& vec);

	static bool Setup();
};
//////////////////////////////////////////////////////////////
#endif